package com.core.ui.bar.footbar;

import java.util.List;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;

import com.core.ui.bar.widget.Menu;
import com.core.ui.bar.widget.MenuItem;

public class FootBar extends LinearLayout implements OnClickListener {
	private String TAG = this.getClass().getName();
	private OnFootClickListener onFootClickListener;
	private Menu menu;

	public FootBar(Context context) {
		super(context);
		init(context);
	}

	public FootBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public FootBar(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	private void init(Context context) {
		setOrientation(LinearLayout.HORIZONTAL);
	}

	public void addMenu(Menu menu) {
		this.menu = menu;
		List<MenuItem> items = menu.getMenuItems();
		int id = 0;
		for (MenuItem item : items) {
			Log.e(TAG, id + "");
			addItem(item, id++);
		}
	}

	/**
	 * @param menu
	 * @param index
	 *            初始位置
	 */
	public void addMenu(Menu menu, int index) {
		this.menu = menu;
		List<MenuItem> items = menu.getMenuItems();
		int id = 0;
		for (MenuItem item : items) {
			Log.e(TAG, id + "");
			addItem(item, id++);
		}
		items.get(index).onClick(index);
	}

	private void addItem(MenuItem item, int id) {
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT, 1);
		item.setGravity(Gravity.CENTER);
		item.setLayoutParams(params);
		item.setId(id);
		item.setOnClickListener(this);
		addView(item);
	}

	@Override
	public void onClick(View v) {
		if (onFootClickListener != null) {
			int index = v.getId();
			switchStyle(index);
			onFootClickListener.onItemClick(this, menu, index);
		}
	}

	public void switchStyle(int index) {
		List<MenuItem> items = menu.getMenuItems();
		for (int i = 0; i < items.size(); i++) {
			MenuItem item = items.get(i);
			if (i == index) {
				item.onClick(i);
			} else {
				item.onUnClick(i);
			}
		}
	}

	public void setOnFootClickListener(OnFootClickListener onFootClickListener) {
		this.onFootClickListener = onFootClickListener;
	}

	public static interface OnFootClickListener {
		void onItemClick(FootBar view, Menu menu, int index);
	}
}
